﻿using System;
using System.Collections.Generic;
using System.Linq;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using System.IO;

namespace Zeus.Components.Nopi.Excel
{
    public abstract class NopiExcelWriter : IDisposable
    {
        protected HSSFWorkbook HssfWorkbook { get; set; }
        protected Sheet Sheet { get; set; }

        public NopiExcelWriter(string sheetName)
        {
            InitializeWorkbook();
            ////Sheet = HssfWorkbook.CreateSheet(ExcelLocalResources.WorksheetName);
            Sheet = HssfWorkbook.CreateSheet(sheetName);
        }

        public void Dispose()
        {
            if (HssfWorkbook != null)
            {
                HssfWorkbook.Dispose();
            }

            if (Sheet != null)
            {
                Sheet.Dispose();
            }
        }

        // protected method to initialize a workbook
        protected void InitializeWorkbook()
        {
            HssfWorkbook = new HSSFWorkbook();

            // create a entry of DocumentSummaryInformation
            var dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            ////dsi.Company = ExcelLocalResources.CompanyName;
            HssfWorkbook.DocumentSummaryInformation = dsi;

            // create a entry of SummaryInformation
            var si = PropertySetFactory.CreateSummaryInformation();
            ////si.Subject = ExcelLocalResources.SummarySubject;
            HssfWorkbook.SummaryInformation = si;
        }

        // protected method to initialize a workbook sheet - could be overridden
        protected virtual void InitializeWorkbookSheet(string sheetName)
        {
            ////Sheet = HssfWorkbook.CreateSheet(ExcelLocalResources.WorksheetName);
            Sheet = HssfWorkbook.CreateSheet(sheetName);
        }

        public MemoryStream WriteToMemoryStream()
        {
            FormatSheet();

            var stream = new MemoryStream();

            // Writing the workbook content to the FileStream...
            HssfWorkbook.Write(stream);

            stream.Position = 0;

            return stream;
        }

        // abstract sheet body build method
        protected abstract void FormatSheet();
    }
}
